<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use app\manage\model\AuthGroupNode;
use app\manage\model\AuthNode;
use buwang\base\AdminBaseController;
use app\manage\model\Admin as AdminModel;
use app\manage\model\Token;
use buwang\service\UserService;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Member;
use app\common\model\SysLog;
use app\common\model\Member as commonMember;
use think\facade\Cache;

class Index extends AdminBaseController
{
    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->layout && $this->app->view->engine()->layout($this->layout);
    }

    /**
     * 首页
     * @return \think\response\View
     */
    public function index()
    {
        return view();
    }

    /**
     * 控制台
     * @return \think\Response
     */
    public function dashboard()
    {
        $system_info['php_uname'] = php_uname();//系统类型及型号
        $system_info['accept_language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';//服务器语言
        $system_info['php_sapi_name'] = php_sapi_name();//获取PHP运行方式
        $system_info['php_version'] = PHP_VERSION;//获取PHP运行版本
        $system_info['zend_version'] = Zend_Version();//获取Zend版本
        $system_info['php_include_path'] = DEFAULT_INCLUDE_PATH;//获取PHP安装路径：
        //$system_info['server_name'] = GetHostByName($_SERVER['SERVER_NAME']);//获取服务器IP：
        //$system_info['system_port'] = $_SERVER['SERVER_PORT'];//  获取服务器Web端口：：
        //$system_info['system_host'] = $_SERVER["HTTP_HOST"];//  获取服务器域名：
        $system_info['server_name'] = isset($_SERVER['SERVER_NAME'])?GetHostByName($_SERVER['SERVER_NAME']):"";//获取服务器IP：
        $system_info['system_port'] = $_SERVER['SERVER_PORT']??'';//  获取服务器Web端口：：
        $system_info['system_host'] = $_SERVER["HTTP_HOST"]??'';//  获取服务器域名：

        $system_info['max_memory'] = get_cfg_var("memory_limit") ? get_cfg_var("memory_limit") : "无";
        $system_info['upload_max_filesize'] = get_cfg_var("upload_max_filesize") ? get_cfg_var("upload_max_filesize") : "不允许上传附件";
        $system_info['max_execution_time'] = get_cfg_var("max_execution_time") . "秒 ";
        //额外信息
        $extend_info['notice'] = "名牛云SAAS平台全新上线了";
        $extend_info['name'] = config('bwsaas.website_name');
        $extend_info['version'] = "V" . config('bwsaas.version');
        $extend_info['website_url'] = config('bwsaas.website_url');
        //上方统计角标
        $member_total = commonMember::addMemberTotal();
        $user_total = commonMember::allUserTotal();
        $recharge_total = commonMember::memberRechargeTotal();
        $app_total = commonMember::memberAppTotal();
        if ($this->request->isAjax()) {
            return $this->success('获取成功', ['extend_info' => $extend_info, 'system_info' => $system_info, 'data' => compact('member_total', 'user_total', 'recharge_total', 'app_total')]);
        } else {
            return view('', ['system_info' => $system_info, 'data' => compact('member_total', 'user_total', 'recharge_total', 'app_total')]);
        }
    }

    /**
     * 菜单
     * @return \think\response\Json
     */
    public function menu()
    {
        $admin = $this->user;
        //TODO :得到登录管理员id
        $adminId = $admin['id'];  //id=1为超级管理员，拥有全部权限
        $logoImage = '/layui/images/logo.png';
        if (isset($admin['avatar']) && $admin['avatar']) $logoImage = $admin['avatar'];

        $homeInfo = [
            'title' => bw_config('backstage_top_title'),
            'href' => bw_config('backstage_top_url'),
        ];
        $logoInfo = [
            'title' => $admin['nickname'],
            'image' => $logoImage,
            'href' => '/'
        ];
        $menuInfo = AdminModel::getMenuList($adminId, ['type' => 'system']);
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }

    /**
     * 登录
     * @return \think\Response
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = [
                'username' => $this->request->param('username/s'),
                'password' => $this->request->param('password/s'),
                'captcha' => $this->request->param('captcha/d'),
            ];

            // 从 Redis 获取验证码
            $hash = Cache::store('redis')->get('login_verify');
            $res = password_verify($data['captcha'], $hash); // 自动识别cost=10
            if (!$res) {
                return $this->error('验证码错误');
            }
            //删除验证码
            Cache::store('redis')->delete('login_verify');

            $this->validate($data, 'Manage.admin_login');

            //验证密码是否正确
            $admininfo = UserService::validateLogin($data['username'], $data['password']);
            $admin = $admininfo['rs'];
            if (!$admin) return $this->error($admininfo['error']);
            $rs = UserService::loginAdmin($admin, true);
            if (!$rs['rs']) return $this->error($rs['error']);
            event('RequestStart', [$this->request, 'admin', '/manage/admin.Index/login', $admin, 200, '', 0, false]);
            return $this->success('登录成功', $rs['rs']);//返回token expires_time
        }
        if ($this->isUserLogin) return $this->redirect('manage/admin/index');
        return view();
    }

    /**
     * 一鍵租户登录
     * @return \think\Response|\think\response\Redirect|\think\response\View
     */
    public function loginMember()
    {
        if ($this->request->isPost()) {
            $data = [
                'mobile' => $this->request->param('mobile/s'),
                'member_id' => $this->request->param('member_id/d'),
                'keeplogin' => $this->request->param('keeplogin', 1),
            ];
            $rule = [
                'mobile|手机号' => 'require',
                'member_id|租户ID' => 'require',
            ];
            $this->validate($data, $rule);
            //判断用户是否存在
            $member = Member::where('mobile', $data['mobile'])->where('id', $data['member_id'])->find();
            if (!$member) return $this->error("租户用户不存在");
            $rs = UserService::loginMember($member, true);
            if (!$rs['rs']) return $this->error($rs['error']);
            $rs['rs']['session_id'] = get_session_id();

            event('RequestStart', [$this->request, 'member', '/manage/member.Index/login', $member, 200, '', 0, false]);
            return $this->success('登录成功', $rs['rs']);
        } else {
            return $this->error("request method error");
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $admin = $this->user;
        $scopes = $this->scopes;
        if ($scopes != 'admin') return $this->error('scopes获取错误');
        if ($this->request->isPost()) {
            if (!$this->token) return $this->error('已退出登录，勿重复点击');

            $res = Token::deleteRedisToken($this->token, $admin['id'], $scopes);
            if (!$res) {
                return $this->error(Token::getError('操作失败'));
            } else {
                return $this->success('退出成功');
            }
        }
    }


    /**
     * 管理员基本资料
     */
    public function userSetting()
    {

        $topAdminId = config('auth.super_admin_id');//超级管理员id
        $admin = $this->user;
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (isset($param['username'])) unset($param['username']);
            if (isset($param['id'])) {
                $result = AdminModel::updateAdmin($param, true);
            } else {
                return $this->error("缺少必要参数");
            }
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(AdminModel::getError());
            }

        }
        if ($this->request->isGet()) {
            $id = $admin['id'];
            $data = AuthGroupAccess::getFind($id);
            if ($topAdminId == $id) $is_super = true; else $is_super = false;
//            $list = AdminModel::select()->toArray();
            if ($this->request->isAjax()) {
                return $this->success('success', ['data' => $data, 'is_super' => $is_super]);
            } else {
                return view('user_setting', ['data' => $data, 'is_super' => $is_super]);
            }
        }
    }

    /**
     * 管理员修改密码
     */
    public function userPassword()
    {
        $topAdminId = config('auth.super_admin_id');//超级管理员id
        $admin = $this->user;
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdminModel::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(AdminModel::getError());
            }

        }
        $id = $admin['id'];
        $data = AuthGroupAccess::getFind($id);
        if ($topAdminId == $id) $is_super = true; else $is_super = false;
        $list = AdminModel::select()->toArray();
        return view('user_password', ['data' => $data, 'list' => $list, 'is_super' => $is_super]);

    }

    /**
     * 得到登录日志
     */
    public function getAdminLoginInfo()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $res = SysLog::getAdminLoginInfo($this->user->id, $page, $limit);
        return $this->success('操作成功', $res);
    }
}
